<template>
	<el-dialog :title="title" width="760" v-model="visible" :close-on-click-modal="false" :destroy-on-close="true" :rules="dataRules" draggable>
		<el-form ref="menuDialogFormRef" :model="form" label-width="110px">
			<div class="blue-card">
				<el-form-item label="资源名称" prop="layerNameCh">
					<el-input v-model="form.layerNameCh" clearable placeholder="请输入" disabled></el-input>
				</el-form-item>
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="类型" prop="dataSourceType">
							<el-select v-model="form.dataSourceType" placeholder="请选择类型" :suffix-icon="IconDropDown" disabled>
								<el-option v-for="item in dataSourceType" :key="item.value" :label="item.label" :value="Number(item.value)" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="格式" prop="dataType">
							<el-select v-model="form.dataType" placeholder="请选择类型" :suffix-icon="IconDropDown" disabled>
								<el-option v-for="item in dataTypeList" :key="item.value" :label="item.label" :value="Number(item.value)" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>

				<el-form-item prop="fileRemarks" label="资源描述" class="mt10">
					<el-input type="textarea" placeholder="请输入资源描述" clearable v-model="form.fileRemarks" disabled />
				</el-form-item>
			</div>
			<el-form-item prop="layerNameCh" label="图层名称" class="mt10">
				<el-input placeholder="请输入图层名称" clearable v-model="form.layerNameCh" />
			</el-form-item>
			<el-form-item prop="projectNameCh" label="图层分组">
				<el-select v-model="form.projectNameCh" :suffix-icon="IconDropDown" placeholder="选择所属项目" @change="handleProject" disabled>
					<el-option v-for="item in projectOptions" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
			</el-form-item>
			<el-form-item prop="layerRemarks" label="图层说明">
				<el-input type="textarea" placeholder="请输入图层说明" clearable v-model="form.layerRemarks" />
			</el-form-item>
			<el-form-item v-if="form.dataType == 4" label="图层名称" show-overflow-tooltip>
				<el-tag color="#E8EAF1">{{ form.layerName }}</el-tag>
			</el-form-item>

			<el-form-item v-if="form.dataSourceType == 2" label="图层组英文名称" show-overflow-tooltip>
				<el-tag color="#E8EAF1">{{ form.projectName }}</el-tag>
			</el-form-item>
			<el-form-item v-if="form.dataType == 4 || form.dataType == 1" label="图层状态">
				<el-tag :color="form.publishStatus == 1 ? '#DAF7C9' : '#E8EAF1'">{{ form.publishStatus == 1 ? '已发布' : '未发布' }}</el-tag>
			</el-form-item>
			<el-form-item v-if="form.labelList && form.labelList.length > 1" prop="label" label="标签">
				<div class="flex gap-2 items-center justify-center">
					<el-tag size="large" v-for="item in form.labelList" :key="item">{{ item }}</el-tag>
				</div>
			</el-form-item>
			<div class="blue-card" v-if="form.dataType == 4 || form.dataType == 1">
				<el-form-item prop="fileNameCh" label="坐标系统">
					<el-select
						filterable
						remote-show-suffix
						remote
						v-model="form.srs"
						:loading="selectLoading"
						:suffix-icon="IconDropDown"
						:remote-method="remoteMethod"
						placeholder="请选择坐标系"
					>
						<el-option v-for="item in srsOptions" :key="item.id" :label="item.name" :value="item.name" />
					</el-select>
				</el-form-item>
				<p></p>
				<div class="mt10">
					<el-row :gutter="20" class="mt10">
						<el-col :span="4">
							<el-text class="mr10 ml20">包围盒边框</el-text>
						</el-col>
						<el-col :span="5">
							<el-input v-model="form.boxMinX" placeholder="最小X" disabled></el-input>
						</el-col>
						<el-col :span="5">
							<el-input v-model="form.boxMinY" placeholder="最小Y" disabled></el-input>
						</el-col>
						<el-col :span="5">
							<el-input v-model="form.boxMaxX" placeholder="最大X" disabled></el-input>
						</el-col>
						<el-col :span="5">
							<el-input v-model="form.boxMaxY" placeholder="最大Y" disabled></el-input>
						</el-col>
					</el-row>
				</div>
				<div class="mt10">
					<el-row :gutter="20" class="mt10">
						<el-col :span="4">
							<el-text class="mr10 ml20">经纬度边框</el-text>
						</el-col>
						<el-col :span="5">
							<el-input v-model="form.latLonBoxMinX" placeholder="最小X" disabled></el-input>
						</el-col>
						<el-col :span="5">
							<el-input v-model="form.latLonBoxMinY" placeholder="最小Y" disabled></el-input>
						</el-col>
						<el-col :span="5">
							<el-input v-model="form.latLonBoxMaxX" placeholder="最大X" disabled></el-input>
						</el-col>
						<el-col :span="5">
							<el-input v-model="form.latLonBoxMaxY" placeholder="最大Y" disabled></el-input>
						</el-col>
					</el-row>
				</div>
				<div class="text-center">
					<el-button class="sum-btn" type="primary" @click="borderCalculation">计算</el-button>
				</div>
			</div>
			<el-form-item v-if="form.dataType == 4 || form.dataType == 1" prop="styleName" label="图层样式" class="mt10">
				<el-select v-model="form.styleName" :suffix-icon="IconDropDown" placeholder="选择图层样式" clearable>
					<el-option v-for="item in styleOptions" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
			</el-form-item>
			<div class="text-center">
				<el-button @click="close()">取消</el-button>
				<el-button type="primary" @click="onSubmit(menuDialogFormRef)">发布</el-button>
			</div>
		</el-form>
	</el-dialog>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { addPost, editPost, getCoordinatelist, getStyle, saveSubmit } from '/@/api/project';
import {
	addGeoLayer,
	getInfoById,
	updateGeoLayer,
	getBorderCalculation,
	getGeoBoxLatLonData,
	getTableDataSourceInfo,
	getGeoBoxDataInfo,
} from '/@/api/resource/layerManagement';
import { useMessage } from '/@/hooks/message';
import { useUserInfo } from '/@/stores/userInfo';
import DropDown from '/@/assets/icons/drop-down.svg';
import { rowContextKey } from 'element-plus';

const visible = ref(false);
const menuDialogFormRef = ref('');
const emit = defineEmits(['refresh']);
const title = ref('编辑图层');
const styleOptions = ref<any[]>([]);
const form = ref({});
const disabled = ref(false);
const selectLoading = ref(false);

const dataList = ref([]);
let selectedRow = reactive(false); // 用来存储当前选中的行
const loading = ref(false);
const state = reactive({});
const activeItem = ref({});
const IconDropDown = {
	render: () => {
		return h('img', { src: DropDown });
	},
};

const srsOptions = ref<any[]>([]);
const checkedCities = ref([]);
const checkList = reactive([
	{
		label: '顶点压缩(有损压缩，如果模型有变形，可取消该选项)',
		value: 0,
	},
	{
		label: '使用实例(Instance)',
		value: 1,
	},
	{
		label: '压缩b3dm',
		value: 2,
	},
	{
		label: '公共纹理嵌入',
		value: 3,
	},
]);
const headers = computed(() => {
	return {
		Accept: 'application/octet-stream',
	};
});

const dataTypeList = ref([
	// 基本底图
	{
		label: '瓦片地图',
		value: '6',
		tip: '选择本地zip格式文件路径上传',
		accept: ['zip'],
	},
	{
		label: '地形',
		value: '7',
		tip: '选择本地zip格式文件路径上传',
		accept: ['zip'],
	},
	{
		label: 'WMS服务',
		value: '8',
		tip: '选择本地zip格式文件路径上传',
		accept: ['zip'],
	},
	// 二维
	{
		label: 'Shapefile',
		value: '1',
		tip: '选择本地zip格式文件路径上传',
		accept: ['zip'],
	},
	{
		label: 'Tif',
		value: '2',
		tip: '选择本地fbx、glb格式文件路径上传',
		accept: ['tif', 'tiff'],
	},
	{
		label: 'PostGIS',
		value: '4',
		tip: '选择本地zip格式文件路径上传',
		accept: ['zip'],
	},
	// 三维
	{
		label: '3Dtiles',
		value: '3',
		tip: '选择本地zip格式文件路径上传',
		accept: ['zip'],
	},
	{
		label: 'FBX/GLB',
		value: '5',
		tip: '选择本地fbx、glb格式文件路径上传',
		accept: ['tif', 'tiff'],
	},
]);

const dataSourceType = ref<any[]>([
	{ label: '基础底图', value: '1' },
	{ label: '二维矢量', value: '2' },
	{ label: '三维模型', value: '3' },
]);

// 表单校验规则
const dataRules = reactive({
	projectName: [{ required: true, message: '图层分组不能为空', trigger: 'blur' }],
	srs: [{ required: true, message: '坐标系不能为空', trigger: 'blur' }],
	layerRemarks: [{ required: true, message: '样式说明不能为空', trigger: 'blur' }],
});

const projectOptions = computed(() => {
	return useUserInfo().userInfos.projectList;
});

const coorForm = ref({
	size: 100,
	current: 1,
	name: '',
});
// 获取坐标系方法
function remoteMethod(val) {
	selectLoading.value = true;
	coorForm.value.name = val;
	setTimeout(() => {
		getCoordinatelist(coorForm.value).then((res) => {
			let { data } = res;
			srsOptions.value = data.records;
			selectLoading.value = false;
		});
	}, 1000);
}

// 获取样式
async function handleProject(projectName: any) {
	const { data } = await getStyle({ projectName });
	styleOptions.value = data.map((item: any) => {
		return {
			label: item.styleNameCh,
			value: item.styleName,
		};
	});
}

const getTableList = async (id) => {
	await getTableDataSourceInfo({ dataSourceId: id }).then((res) => {
		for (let i = 0; i < res.data.length; i++) {
			if (res.data[i].tableName == form.value.layerName) {
				form.value.columnName = res.data[i].columnName;
				form.value.tableName = res.data[i].tableName;
			}
		}
	});
};

// 边框计算
const borderCalculation = async () => {
	if (!form.value.srs) {
		useMessage().error('请选择坐标系统！');
		return;
	}
	try {
		loading.value = true;
		const { data } = await getBorderCalculation({
			columnName: form.value.columnName,
			tableName: form.value.tableName,
			wokeSpaceName: form.value.wokeSpaceName,
			storeName: form.value.storeName,
			srs: form.value.srs,
		});
		form.value.latLonBoxMinX = data.boxMinx;
		form.value.latLonBoxMinY = data.boxMiny;
		form.value.latLonBoxMaxX = data.boxMaxx;
		form.value.latLonBoxMaxY = data.boxMaxy;
		LatLonCalculation();
	} catch (err: any) {
		// useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};
// 经纬度计算
const LatLonCalculation = async () => {
	try {
		loading.value = true;
		const { data } = await getGeoBoxLatLonData({
			srs: form.value.srs,
			boxMinx: form.value.boxMinX,
			boxMiny: form.value.boxMinY,
			boxMaxx: form.value.boxMaxX,
			boxMaxy: form.value.boxMaxY,
		});
		form.value.boxMinX = data.boxMinx;
		form.value.boxMinY = data.boxMiny;
		form.value.boxMaxX = data.boxMaxx;
		form.value.boxMaxY = data.boxMaxy;
	} catch (err: any) {
		// useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

const isSelected = (value) => {
	return selectedRow == value;
};
const handleSelectionChange = (value) => {
	if (isSelected(value)) {
		nextTick(() => {
			selectedRow = false;
		});
	} else {
		selectedRow = value;
	}
	// console.log(selectedRow);
};

const close = () => {
	visible.value = false;
	form.value = {};
};

//表单提交
const onSubmit = async (forms) => {
	await forms.validate((valid) => {
		if (valid) {
			if (form.value.dataType == 4) {
				form.value.layerName = activeItem.value.layerName;
				form.value.dataSourceId = activeItem.value.dataSourceId;
				form.value.storeName = activeItem.value.storeName;
			}
			delete form.value.onEnable;
			delete form.value.defaultStr;
			delete form.value.wokeSpaceBack;
			delete form.value.projectNameCh;
			delete form.value.firstLabel;
			delete form.value.secondLabel;
			delete form.value.thirdLabel
			delete form.value.columnName;
			delete form.value.tableName;
			updateGeoLayer(form.value)
				.then((res) => {
					if (res.msg) {
						if(res.code==0){
						useMessage().success(res.msg);	
						visible.value = false;
						reset();
						emit('refresh');
						}
					
					}
				})
				.catch((res) => {
					// useMessage().error(res.msg);
				});
		}
	});
};

//重置表单
const reset = () => {
	form.value = {
		wokeSpaceName: '',
		onEnable: true,
		defaultStr: false,
		wokeSpaceBack: '',
	};
};
async function openDialog(row: any) {
	disabled.value = false;
	visible.value = true;
	try {
		loading.value = true;
		const { data } = await getGeoBoxDataInfo(row.layerManagerId);
		activeItem.value = data;
		nextTick(() => {
			Object.assign(form.value, data);
			if (row.dataType == 4) {
				getTableList(data.dataSourceId);
				handleProject(data.projectName);
			}
			if (row.dataType == 1) {
				handleProject(data.projectName);
			}
			if (!activeItem.value.labelList) {
				activeItem.value.labelList = [];
			}
		});
	} catch (err: any) {
		// useMessage().error(err.msg);
	} finally {
	}
}

defineExpose({
	openDialog,
	reset,
});
</script>
<style scoped lang="scss">
.text-center {
	text-align: right;
	margin-top: 18px;
}
.preview {
	position: absolute;
	left: 110px;
	color: #0768ad;
	text-decoration: underline;
}
.sum-btn {
	width: 180px;
}
p {
	width: 97%;
	text-align: center;
	border-bottom: 1px solid #1580cd;
	line-height: 1px;
	margin: 8px 20px;
}
.blue-card {
	margin: 5px 5px 20px 5px;
	padding: 10px;
	background: #edf0f7;
	padding-left: 0px;
}
.table-left {
	width: 98.6%;
	height: 180px;
	margin: auto;
	border: 1px solid #3156a5;
}
</style>
